#!/bin/bash

sed -i /^ec2-user/d /etc/sudoers
userdel -r ec2-user
sed -i /^Permit/s/forced-commands-only/without-password/ /etc/ssh/sshd_config
sed -i /^X11Forwarding/d /etc/ssh/sshd_config
service sshd reload

instanceid=`curl -s http://169.254.169.254/latest/meta-data/instance-id`
region=`curl -s http://169.254.169.254/latest/meta-data/placement/availability-zone |sed 's/.$//'`
certname=`curl -s http://169.254.169.254/latest/meta-data/public-hostname`
account=`aws iam list-account-aliases | grep -oP "(?<=\"gu-)[^\"]+"`
apptag=`aws ec2 describe-tags --filters "Name=resource-id,Values=$instanceid" "Name=resource-type,Values=instance" "Name=key,Values=App" --region $region | grep -oP "(?<=\"Value\": \")[^\"]+"`
stacktag=`aws ec2 describe-tags --filters "Name=resource-id,Values=$instanceid" "Name=resource-type,Values=instance" "Name=key,Values=Stack" --region $region | grep -oP "(?<=\"Value\": \")[^\"]+"`
stagetag=`aws ec2 describe-tags --filters "Name=resource-id,Values=$instanceid" "Name=resource-type,Values=instance" "Name=key,Values=Stage" --region $region | grep -oP "(?<=\"Value\": \")[^\"]+"`

cat > /etc/facts.txt <<__END__
aws_account=$account
certname=$certname
region=$region
aws_region=$region
app=$apptag
stack=$stacktag
stage=$stagetag
__END__

for f in $(</etc/facts.txt); do eval export FACTER_$f; done

cat >/etc/puppet/puppet.conf <<__END__
[main]
certname = $certname
logdir = /var/log/puppet
pluginsync = true
rundir = /var/run/puppet
ssldir = \$vardir/ssl

[agent]
__END__

if [ "$stage" != "INFRA" -a "$stage" != "PROD" -a "$stage" != "" ]; then
	echo 'environment = development' >>/etc/puppet/puppet.conf
fi
echo 'report = true' >>/etc/puppet/puppet.conf

server=`dig +short CNAME bootstrap.example.com`

while true; do
	if [ -n "$server" ]; then
		puppet agent --color false --no-daemonize --detailed-exitcodes \
			--environment bootstrap --ignoreschedules --onetime --server "${server%?}" \
			--no-splay --waitforcert=30
		[ $? -eq 0 -a -f `puppet agent --configprint hostcert` ] && break
	fi
	sleep 10
done

while true; do
	if [ -n "$server" ]; then
		puppet agent --color false --no-daemonize --detailed-exitcodes \
			--ignoreschedules --onetime --server "${server%?}" --no-splay
		[ $? -eq 0 ] && break
	fi
	sleep 10
done

chkconfig puppet on
service puppet start
